package com.ruike.alisurface.ui.answerQuestion;

import android.os.Environment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.mqtt.MQTTService;
import com.ruike.alisurface.mqtt.ServiceUtils;
import com.ruike.alisurface.services.NetWorkListenerService;
import com.ruike.alisurface.ui.answerQuestion.adapter.QuestionProductAdapter;
import com.ruike.alisurface.ui.answerQuestion.bean.QuestionProductBean;
import com.ruike.alisurface.ui.answerQuestion.http.TongNuoHttp;
import com.ruike.alisurface.ui.dialog.CustomDialog;
import com.ruike.alisurface.ui.mainPage.VedioAdvActivity;
import com.ruike.alisurface.utils.GlideImageLoader;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_utils.FileUtils;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;
import com.voodoo.lib_utils.imageLoader.ImageLoader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Author: voodoo
 * CreateDate: 2023/11/22 022上午 11:07
 * Description: 答题商品界面
 */
public class QuestionProductListActivity extends BaseAty implements QuestionProductAdapter.OnProductClickListener {

    @BindView(R.id.questionProduct_toSetting_view)
    View toSettingView;
    @BindView(R.id.questionProduct_countdownTime_tv)
    TextView countdownTimeTv;
    @BindView(R.id.questionProduct_goodsList_recv)
    RecyclerView productListRev;
    @BindView(R.id.questionProduct_bg_imgv)
    ImageView bgImgv;
    @BindView(R.id.questionProduct_top_imgv)
    ImageView topImgv;

    boolean isOpenAdv = false;

    QuestionProductAdapter adapter;
    List<QuestionProductBean.DataBean> productList;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_question_product;
    }

    @Override
    protected void initViews() {
        isOpenAdv = ShareUtils.getInstance().getInt(ShareKey.ADV_TYPE, Constant.ADV_TYPE_NONE) != Constant.ADV_TYPE_NONE;
        L.i(isOpenAdv ? "有广告" : "无广告");
//        initTitleBar(!isOpenAdv);
        if (isOpenAdv) {
            startCountdownTimer(300, countdownTimeTv, null);
            toSettingView.setOnClickListener(view -> {
                continuousClick();
            });
        } else {
            countdownTimeTv.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initData() {
        // 答题商品列表背景图片文件列表
        File[] bgImageFiles = FileUtils.getFolderFileList(
                Environment.getExternalStorageDirectory() + File.separator + "picture" + File.separator + "questionProductBgImage");
        if (bgImageFiles == null || bgImageFiles.length <= 0) {
            bgImgv.setVisibility(View.INVISIBLE);
        } else {
            GlideImageLoader.loadImage(this, bgImageFiles[0].getAbsolutePath(), bgImgv);
        }
        // 答题商品列表头部图片文件文件列表
        File[] topImgFiles = FileUtils.getFolderFileList(Environment.getExternalStorageDirectory()
                + File.separator + "picture" + File.separator + "questionProductTopImage");
        if (topImgFiles == null || topImgFiles.length <= 0) {
            topImgv.setVisibility(View.INVISIBLE);
        } else {
            GlideImageLoader.loadImage(this, topImgFiles[0].getAbsolutePath(), topImgv);
        }
    }

    @Override
    public void doEventBusResult(MsgEventBus event) {
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!ServiceUtils.isServiceRunning(this, MQTTService.class.getName())) {
            L.e("MQTTService服务未启动，启动Mqtt");
            ServiceUtils.startService(this, MQTTService.class);
        }
        if (!ServiceUtils.isServiceRunning(this, NetWorkListenerService.class.getName())) {
            L.e("NetWorkListenerService服务未启动，启动NetWorkService");
            ServiceUtils.startService(this, NetWorkListenerService.class);
        }
        if (isOpenAdv) {
            startCountdownTimer(120, countdownTimeTv, null);
        }

        productList = new ArrayList<>();
        adapter = new QuestionProductAdapter(QuestionProductListActivity.this, productList, QuestionProductListActivity.this);
        productListRev.setAdapter(adapter);
        productListRev.setLayoutManager(new GridLayoutManager(this, 4));

        showProgressDialog("正在获取商品列表...");
        TongNuoHttp.getProductList(this);
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        if (TongNuoHttp.GET_PRODUCT_LIST_URL.contentEquals(requestUrl)) {
            QuestionProductBean questionProductBean = GsonUtils.json2Model(requestJsonStr, QuestionProductBean.class);
            productList = questionProductBean.getData();
            if (productList != null && productList.size() > 0) {
                adapter.setItem(productList);
            }
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
        if (TongNuoHttp.GET_PRODUCT_LIST_URL.contentEquals(requestUrl)) {
            showErrorTip(errorMsg);
            startCountdownTimer(3, countdownTimeTv, null);
        }
    }

    @Override
    public void onProductItemClickListener(int index, QuestionProductBean.DataBean dataBean) {
        if (dataBean.getSlot_count() <= 0) {
            showErrorTip("此商品已售罄，请选择其他商品");
            return;
        }
        new CustomDialog.Builder(this)
                .setTitle("操作提示")
                .setMessage("确认选择此商品，并进行答题？<br>此商品需答" + dataBean.getSet_question_count() + "道题，并回答正确" + dataBean.getSet_pass_count() + "题。")
                .setNegativeButton("取消", null)
                .setPositiveButton("确定", (dialogInterface, i) -> {
                    ShareUtils.getInstance().putString(ShareKey.STRATEGY_ID_KEY, dataBean.getStrategy_id());
                    L.i("保存的策略ID：" + dataBean.getStrategy_id());
                    startActivity(AnswerQuestionActivity.class, null);
                    finish();
                }).create().show();
    }

}
